package com.wish233.bootstrap.provider;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import com.wish233.application.RpcApplication;
import com.wish233.config.RegistryConfig;
import com.wish233.config.RpcConfig;
import com.wish233.model.register.ServiceMetaInfo;
import com.wish233.register.Registry;
import com.wish233.register.factory.RegistryFactory;
import com.wish233.register.local.LocalServiceRegister;
import com.wish233.server.WRpcServer;
import com.wish233.server.impl.VertxNetServer;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @author WHH
 * 消费者快速启动
 */
public class ProviderBootStrap {

    public static void start(List<ProviderRegisterInfo> infoList) {
        // RPC 框架初始化
        RpcApplication.init();
        // 注册服务
        for (ProviderRegisterInfo info : infoList) {
            String serviceName = info.getServiceName();
            Class<?> implClass = info.getImplClass();
            //本地注册
            LocalServiceRegister.registerService(serviceName, implClass);
            ((Logger) LoggerFactory.getLogger("io.grpc.netty")).setLevel(Level.INFO);
            // 注册服务到注册中心
            RpcConfig rpcConfig = RpcApplication.getRpcConfig();
            RegistryConfig registryConfig = rpcConfig.getRegistryConfig();
            Registry registry = RegistryFactory.getInstance(registryConfig.getRegistry());
            ServiceMetaInfo serviceMetaInfo = new ServiceMetaInfo();
            serviceMetaInfo.setServiceName(serviceName);
            serviceMetaInfo.setServiceHost(rpcConfig.getServerHost());
            serviceMetaInfo.setServicePort(rpcConfig.getServerPort());
            try {
                registry.register(serviceMetaInfo);
            } catch (Exception e) {
                throw new RuntimeException("服务:" + serviceName + " 实现类:" + implClass.getName() + "注册失败！", e);
            }
        }
        // 启动 web 服务
        WRpcServer netServer = new VertxNetServer();
        netServer.start(RpcApplication.getRpcConfig().getServerPort());
    }

}
